package com.android.panballgame;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PBGame extends Activity implements SensorEventListener {
	
	final PBEngine engine = new PBEngine();	

	private PBGameView gameView;
	private SensorManager sm;
	private Sensor accSensor;
	private Chronometer chron;
	private Button ctn, save, end, restart;
	public static ImageButton stop, again, next, end2, rank2;
	public static ImageView msgcon, msgclear, subdark, subback, msgover;
	public TextView text, text2, starttxt, textlevel, textcoin;
	private Toast t = null;
	private int back = 0;
	String TAG = "logcat";
	static float accX, accY, accZ;
	boolean sound6 = false;
	public int over;

	final StringBuffer msg_hole = new StringBuffer(), msg_save = new StringBuffer();//알림 메시지 버퍼
	// 효과음 객체
	private static PBSound sound;

	@SuppressWarnings("deprecation")
	@SuppressLint("InlinedApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		
		if (!PBMusic.player.isPlaying() && PBEngine.isMusic==1){
			PBMusic.isRunning = true;
			PBMusic.player.start();
		}
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.game);
		
		gameView = (PBGameView) findViewById(R.id.surface_view);
				
		// 일시정지 버튼
		stop = (ImageButton) findViewById(R.id.btnStop);
		again = (ImageButton) findViewById(R.id.btnAgain);
		end2 = (ImageButton) findViewById(R.id.btnEnd);
		next = (ImageButton) findViewById(R.id.btnNext);
		rank2 = (ImageButton) findViewById(R.id.btnRanking);
		msgcon = (ImageView) findViewById(R.id.msgcon);
		msgclear = (ImageView) findViewById(R.id.msgclear);
		msgover = (ImageView) findViewById(R.id.msgover);
		subdark = (ImageView) findViewById(R.id.subdark);
		subback = (ImageView) findViewById(R.id.subback);	
		textlevel = (TextView) findViewById(R.id.textlevel);				
		textcoin = (TextView) findViewById(R.id.textcoin);
		
		initialize();
		over = 1;
		
		sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		accSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		/** oriSensor = sm.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); */

		sound = new PBSound();
		sound.initSounds(getBaseContext());
		sound.addSound(1, R.raw.sound1);
		sound.addSound(2, R.raw.sound2);
		sound.addSound(3, R.raw.sound3);
		sound.addSound(4, R.raw.sound4);
		sound.addSound(5, R.raw.sound5);
		sound.addSound(6, R.raw.sound6);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);																		

		stop.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		stop.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);
		again.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		again.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);
		end2.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		end2.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);
		next.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		next.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);
		rank2.getBackground().setAlpha(PBEngine.MENU_BUTTON_ALPHA);
		rank2.setHapticFeedbackEnabled(PBEngine.HAPTIC_BUTTON_FEEDBACK);
		
		again.setOnClickListener(restart_clickListener);
		next.setOnClickListener(next_clickListener);
		end2.setOnClickListener(end_clickListener);
		rank2.setOnClickListener(rank_clickListener);
		
		stop.setOnClickListener(new ImageButton.OnClickListener() {

			@Override
			public void onClick(View v) {// 일시정지 버튼
				// TODO Auto-generated method stub
				if (back == 0) {
					gameView.onPause();
					PBEngine.time = chron.getBase() - SystemClock.elapsedRealtime();
					chron.stop();
					if (PBMusic.player.isPlaying())
						PBMusic.player.pause();

					showDialog(PBEngine.PAUSE_DIALOG);
					back++;
				} else {
					gameView.onPause();
					if (PBMusic.player.isPlaying())
						PBMusic.player.pause();

					showDialog(PBEngine.PAUSE_DIALOG);
				}
			}
		});	
		
	}

	
	private Button.OnClickListener continue_clickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			gamestart();
			dismissDialog(PBEngine.PAUSE_DIALOG);
			back--;
		}
	};

	private Button.OnClickListener save_clickListener = new Button.OnClickListener() {	// save 버튼
		@Override
		public void onClick(View v) {			
			if (!PBMusic.player.isPlaying() && PBEngine.isMusic == 1)
				PBMusic.player.start();
			
			if(PBEngine.level == 1)
				PBEngine.time_level1 = PBEngine.time; 
			else if(PBEngine.level == 2)
				PBEngine.time_level2 = PBEngine.time - PBEngine.time_level1;
			else 
				PBEngine.time_level3 = PBEngine.time - PBEngine.time_level2 - PBEngine.time_level1 ; 

			if(PBEngine.isDb ==1){
				PBMainMenu.db_updatemain();
				PBMainMenu.db_updatelevel();
				msg_save.append("데이터 덮어쓰기 완료");			 
				Toast.makeText(PBGame.this, msg_save.toString(), Toast.LENGTH_SHORT).show();
			}
			else{
				PBMainMenu.db_addmain();
				PBMainMenu.db_addlevel();
				
				msg_save.append("데이터 저장 완료");
				Toast.makeText(PBGame.this, msg_save.toString(), Toast.LENGTH_SHORT).show();
			}
		
				PBMainMenu.db_getlevel();

			msg_save.setLength(0);
		}
	};
	// end !! 게임 activity 종료
	private Button.OnClickListener end_clickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {		
			if (!PBMusic.player.isPlaying() && PBEngine.isMusic == 1)
				PBMusic.player.start();
			finish();
			PBEngine.useDb = 0;
			
		}
	};
	
	private Button.OnClickListener restart_clickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub end !! 게임 재시작
			PBEngine.level--;
			PBEngine.useDb = 0;
			makestage();
			
		}
	};

	private Button.OnClickListener next_clickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			// next  다음 레벨로
			if(PBEngine.level == 1)
				PBEngine.time_level1 = PBEngine.time; 
			else if(PBEngine.level == 2)
				PBEngine.time_level2 = PBEngine.time - PBEngine.time_level1;

			PBEngine.extend_time = 1;
			PBEngine.useDb = 0;
			makestage();
			PBEngine.extend_time = 0;
		}
	};
	private Button.OnClickListener rank_clickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub end !! rank 등록하러
			PBEngine.dbtime = (int) PBEngine.time;
			finish();
			
			Intent dbserver = new Intent(getApplicationContext(), PBWebView.class);
			PBGame.this.startActivity(dbserver);		
			
			if (!PBMusic.player.isPlaying() && PBEngine.isMusic == 1)
				PBMusic.player.start();		
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		Dialog dialog = null;
		switch (id) {
		case PBEngine.PAUSE_DIALOG:
			dialog = new Dialog(PBGame.this);
			dialog.setContentView(R.layout.popup);
			dialog.setTitle("일시정지");

			ctn = (Button) dialog.findViewById(R.id.button1);
			save = (Button) dialog.findViewById(R.id.button2);
			end = (Button) dialog.findViewById(R.id.button3);
			restart = (Button) dialog.findViewById(R.id.button4);

			ctn.setOnClickListener(continue_clickListener);
			save.setOnClickListener(save_clickListener);
			end.setOnClickListener(end_clickListener);
			restart.setOnClickListener(restart_clickListener);

			break;
			default:
				dialog = null;
		}	
		return dialog;
	}

	public static void sound(int s) {
		if (s == 1)
			sound.playSound(1);
		else if (s == 2)
			sound.playSound(2);
		else if(s ==3)
			sound.playSound(3);
		else if(s ==4)
			sound.playSound(4);
		else if(s ==5)
			sound.playSound(5);
		else if(s ==6)
			sound.playSound(6);
	}

	@Override
	protected void onResume() {
		super.onResume();
		gameView.onResume();
		sm.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_NORMAL);

	}

	@Override
	protected void onPause() {
		super.onPause();
		gameView.onPause();
		sm.unregisterListener(this);
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		synchronized (this) {
			float var0 = event.values[0];
			float var1 = event.values[1];
			float var2 = event.values[2];
			int remain2;// 남은 과제수가 - 되는걸 방지
			if (PBEngine.remain >= 0)
				remain2 = PBEngine.remain;
			else
				remain2 = 0;
			textcoin.setText("남은 과제 수 : " + remain2);
			
			if (PBEngine.WAIT) {// 게임 끝 다열로그 뜰 때
				PBEngine.WAIT = false;
				gamepause();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				visible(PBEngine.level);
			}
			else if(PBEngine.HOLE && PBEngine.remain > 0 ){//막는 효과음 나는게 좋을듯
				if(t == null){
				msg_hole.append("남은 필수 과제를 다 수행하세요.");
				t = Toast.makeText(PBGame.this, msg_hole.toString(), Toast.LENGTH_SHORT);
				}				
				t.show();
				PBEngine.HOLE = false;
				msg_hole.setLength(0);
			}
			else if(PBEngine.MINUS_TIME){//시간 10초 줄이기
				PBEngine.time = chron.getBase() - SystemClock.elapsedRealtime();
				chron.setBase(SystemClock.elapsedRealtime() + PBEngine.time + 10000);// time: -경과한 시간(msec)
				PBEngine.MINUS_TIME = false;
			}
			
			PBEngine.time2 = chron.getBase() - SystemClock.elapsedRealtime();
			if(PBEngine.time2 <= -301000 ){//total time이 5분을 넘기면 게임아웃
				if (over == 1) {
					over = 0;
					gameover();
				}
				PBEngine.time2 = 0;
				PBEngine.time = 0;
				PBEngine.time_level1 = 0;
				PBEngine.time_level2 = 0;
				PBEngine.time_level3 = 0;
				PBEngine.level = 1;
				gamepause();
				
				visible2();				
			}
			
			switch (event.sensor.getType()) {
			case Sensor.TYPE_ACCELEROMETER:

				accX = var0;
				accY = var1;
				accZ = var2;

				break;

			}
		}
	}

	private void initChron(long time) {
		chron = (Chronometer) findViewById(R.id.chron);
		chron.setBase(SystemClock.elapsedRealtime() + time);
		chron.start();
	}
	
	private void gameover(){
		PBGame.sound(6);//게임 오버 효과음
	}
	
	public void surfaceDestroyed(SurfaceHolder holder) {
		onPause();
	}
	
	//게임 초기화 하기
	protected void initialize(){
			
		if(PBEngine.useDb == 1){//db 내용 불러오면
			initChron(PBEngine.time);// 타이머 시작
			if(PBEngine.level == 1){
				textlevel.setText("LEVEL 1");
			}
			else if(PBEngine.level == 2){
				textlevel.setText("LEVEL 2");
			}
			else if(PBEngine.level == 3){
				textlevel.setText("LEVEL 3");
			}
		} 
		else {
			if (PBEngine.extend_time == 1) {// 이전 스테이지에서 넘어온 경우
				initChron(PBEngine.time);
				} 
			else {// 새로시작하는 게임(1, 2, 3 있음)restart포함
				if (PBEngine.level == 1) {
					PBEngine.time_level1 = 0;
					PBEngine.time_level2 = 0;
					PBEngine.time_level3 = 0;
					initChron(PBEngine.time_level1);// 타이머 시작
				} 
				else if (PBEngine.level == 2) {
					PBEngine.time_level2 = 0;
					PBEngine.time_level3 = 0;
					initChron(PBEngine.time_level1);
				} 
				else if (PBEngine.level == 3) {
					PBEngine.time_level3 = 0;
					initChron(PBEngine.time_level1 + PBEngine.time_level2);
				}
			}
			if (PBEngine.level == 1) {
				PBEngine.time_level1 = 0;
				textlevel.setText("LEVEL 1");
				PBEngine.remain = 4;
			}
			else if(PBEngine.level == 2){
				PBEngine.time_level2 = 0;
				textlevel.setText("LEVEL 2");
				PBEngine.remain = 5;				
			}
			else if(PBEngine.level == 3){
				PBEngine.time_level3 = 0;
				textlevel.setText("LEVEL 3");
				PBEngine.remain = 7;				
			}
		}			
	}
	@Override
	public boolean onKeyDown(int KeyCode, KeyEvent event) {
		switch (KeyCode) {
		case KeyEvent.KEYCODE_BACK:// 뒤로가기 버튼
			if (back == 0) {
				gamepause();

				showDialog(PBEngine.PAUSE_DIALOG);
				back++;
			} 
			else {
				gameView.onPause();
				if (PBMusic.player.isPlaying())
					PBMusic.player.pause();

				showDialog(PBEngine.PAUSE_DIALOG);
			}
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	  protected void onUserLeaveHint() {
	   // TODO Auto-generated method stub
				boolean clean = false;
				clean = engine.onExit();
				if (clean) {
					int pid = android.os.Process.myPid();
					android.os.Process.killProcess(pid);
				}
				System.exit(0);
		super.onUserLeaveHint();
	  }
	
	private void gamepause(){
		gameView.onPause();	
		PBEngine.time = chron.getBase() - SystemClock.elapsedRealtime();
		chron.stop();

		if (PBMusic.player.isPlaying())
			PBMusic.player.pause();
	}
	private void gamestart(){
		if (PBEngine.isMusic ==1 && !PBMusic.player.isPlaying())
			PBMusic.player.start();
		
		gameView.onResume();
		chron.setBase(SystemClock.elapsedRealtime() + PBEngine.time);// time: -경과한 시간(msec)
		chron.start();
	}
	public long getchron(){
		return PBEngine.time; 
	}
	public void setchron(long time){
		time = chron.getBase() - SystemClock.elapsedRealtime();
	}
	private void makestage(){
			
		PBEngine.level++;
		finish();
		if (PBEngine.isMusic ==1&& !PBMusic.player.isPlaying())
			PBMusic.player.start();
		
		if(PBEngine.level == 1){
			Intent game = new Intent(getApplicationContext(), PBGame.class);
			this.startActivity(game);
		}
		else if(PBEngine.level == 2){		
			Intent game2 = new Intent(getApplicationContext(), PBGame.class);
			this.startActivity(game2);
		}
		else if(PBEngine.level == 3){
			Intent game3 = new Intent(getApplicationContext(), PBGame.class);
			this.startActivity(game3);
		}
	}
	public static void visible(int level){//일시정지버튼, 뒤로가기 막아두기  + 축하 효과음
		if(level < 3){
			msgcon.setVisibility(1);
			next.setVisibility(1);
		}
		else{
			msgclear.setVisibility(1);
			rank2.setVisibility(1);
		}
		again.setVisibility(1);	
		subdark.setVisibility(1);
		subback.setVisibility(1);
		end2.setVisibility(1);
	}
	private void visible2(){//레벨1부터 0.0부터 다시시작
		msgover.setVisibility(1);
		again.setVisibility(1);	
		subdark.setVisibility(1);
		subback.setVisibility(1);
		end2.setVisibility(1);
	}
	
}
